package com.duowan.cms.domain.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.duowan.cms.domain.channel.Channel;
import com.duowan.cms.domain.channel.rpst.ChannelRepository;
import com.duowan.cms.common.domain.DomainObject;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.common.webapp.content.SpringApplicationContextHolder;
import com.duowan.cms.dto.user.UserPowerInfo;
import com.duowan.cms.dto.user.UserRole;

/**
 * 用户在某个具体频道下的权限
 * 
 * @author coolcooldee
 * @version 1.0
 * @created 10-九月-2012 13:45:55
 */
public class UserPower implements DomainObject {
    
    private static final long serialVersionUID = 8866797911832762261L;
    
    /**
     * 用户唯一标识
     */
    private String userId;
    /**
     * 频道唯一标识
     */
    private Channel channel;
    /**
     * 创建时间
     */
    private Date createTime;
    /**
     * 最后修改时间
     */
    private Date lastModifyTime;
    /**
     * 创建该用户的管理员ID
     */
    private String adminId;
    
    /**
     * 权限值（共32位，每位代表一种权限。0代表没有权限，1代表有权限， 其中第一位未字母，其它的30位为数字0/1
     * 第一位未字母代表身份：分别为s,a,h,o,d，对应超级管理员，系统管理员，主编辑，普通编辑，审核员，实习生）
     * 另外的30位所代表的权限，对应allPowerMap的值
     */
    private String value;
    
    /**
     * 获取用户的角色，根据权限值的第一位数来判断，分别为s,a,h,o,d，对应超级管理员，系统管理员，主编辑，普通编辑，审核员，实习生）
     */
    public UserRole getUserRole() {
        if (StringUtil.isEmpty(this.value))
            return null;
        return UserRole.getInstance(this.value.charAt(0) + "");
    }
    
    /**
     * 获取在该身份默认赋予的权限下，额外增加的权限
     * @return
     */
    public List<Power> getAdded(){
        List<Power> list = new ArrayList<Power>();
        String exactValue = this.getUserRole().getExactValue();
        int exactValueLength = exactValue.length();
        for(int i=0; i<exactValueLength; i++){
            String key = (i+1)+"";
            if(exactValue.charAt(i)=='0' && value.charAt(i+1)=='1' && !StringUtil.isEmpty(Power.getAllPowerMap().get(key))){
                list.add(new Power(key, Power.getAllPowerMap().get(key)));
            }
        }
        return list;
    }
    
    
    /**
     * 获取在该身份默认赋予的权限下，别另外去除的权限
     * @return
     */
    public List<Power> getRemoved(){
        List<Power> list = new ArrayList<Power>();
        String exactValue = this.getUserRole().getExactValue();
        int exactValueLength = exactValue.length();
        for(int i=0; i<exactValueLength; i++){
            String key = (i+1)+"";
            if(exactValue.charAt(i)=='1' && value.charAt(i+1)=='0' && !StringUtil.isEmpty(Power.getAllPowerMap().get(key))){
                list.add(new Power(key , Power.getAllPowerMap().get(key)));
            }
        }
        return list;
    }
    
    /**
     * 获取所拥有的权限，返回Map，key为权限的唯一标识，value为权限的名字
     * 
     * @return
     */
    public List<Power> getOwnPower() {
        if (this.value == null)
            return null;
        int length = this.value.length();
        List<Power> list = new ArrayList<Power>();
        for (int i = 1; i < length; i++) { // 顺序遍历value，索引i从1开始，忽略0的身份位
            if ('1' == this.value.charAt(i)) { // 值为 1，表示拥有该权限
                list.add(new Power(i + "", Power.getAllPowerMap().get(i + "")));
            }
        }
        return list;
    }
    
    public UserPower(UserPowerInfo userPowerInfo) {
        this.createTime = new Date();
        this.update(userPowerInfo);
    }
    
    public UserPower() {
        
    }
    
    public void update(UserPowerInfo userPowerInfo) {
        this.adminId = userPowerInfo.getAdminId();
        if (userPowerInfo.getChannelInfo() == null) {
            this.channel = null;
        } else {
            this.channel = this.getChannelRepository().getById(userPowerInfo.getChannelInfo().getId());
        }
        this.lastModifyTime = new Date();
        this.userId = userPowerInfo.getUserId();
        // 转成32位的串
        this.value = this.getValueFromUserPowerInfo(userPowerInfo);
    }
    
    private String getValueFromUserPowerInfo(UserPowerInfo userPowerInfo){
        StringBuffer resultValue = new StringBuffer();
        StringBuffer tempValueSB = new StringBuffer();
        for(int i=0; i<userPowerInfo.getOwnPowers().size(); i++){
            tempValueSB.append(",").append(userPowerInfo.getOwnPowers().get(i).getId());
        }
        tempValueSB.append(",");
        String tempValue = tempValueSB.toString();
        int length = 32;
        for(int i=0; i<length; i++){
            if(i==0){
                resultValue.append(userPowerInfo.getUserRole().getValue());
            }else{
                if((tempValue).indexOf(","+i+",")>-1){
                    resultValue.append("1");
                }else{
                    resultValue.append("0");
                }
            }
        }
        return resultValue.toString();
    }
    
    private ChannelRepository getChannelRepository() {
        return SpringApplicationContextHolder.getBean("channelRepository",
                ChannelRepository.class);
    }
    
    public String getUserId() {
        return userId;
    }
    
    public void setUserId(String userId) {
        this.userId = userId;
    }
    
    public Channel getChannel() {
        return channel;
    }
    
    public void setChannel(Channel channel) {
        this.channel = channel;
    }
    
    public Date getCreateTime() {
        return createTime;
    }
    
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    
    public Date getLastModifyTime() {
        return lastModifyTime;
    }
    
    public void setLastModifyTime(Date lastModifyTime) {
        this.lastModifyTime = lastModifyTime;
    }
    
    public String getAdminId() {
        return adminId;
    }
    
    public void setAdminId(String adminId) {
        this.adminId = adminId;
    }
    
    public String getValue() {
        return value;
    }
    
    public void setValue(String value) {
        this.value = value;
    }
    
}